//
//  WBHomePictureView.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/10.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit
import SDWebImage

// 设置间距
private let ItemMarin: CGFloat = 5
// 计算每项宽度
private let ItemWidth: CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMarin) / 3


class WBHomePictureView: UICollectionView {

    var picUrls: [WBHomePicInfo]? {
        
        didSet {
            
            messageLabel.text = "\(picUrls?.count ?? 0)"
            
            guard let currentPicurls = picUrls else {
                
                return
            }
            
            if currentPicurls.count > 0 {
                
                calcPictureViewSize(count: picUrls?.count ?? 0)
            }
            
            reloadData()
        }
    }
    
    private lazy var messageLabel: UILabel = {
       
        let label = UILabel(fontSize: 20, textColor: UIColor.red)
        return label
        
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        
        flowLayout.minimumLineSpacing = ItemMarin
        
        flowLayout.minimumInteritemSpacing = ItemMarin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        register(WBHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewCell_id)
        
        dataSource = self
        
        addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            
            make.center.equalTo(self)
        }
        
    }
    
    private func calcPictureViewSize(count: Int) {
        
        if count == 1 {
            
            let imageUrl = picUrls!.first!.thumbnail_pic!
            
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                
                var imageSize = localImage.size
                
                if imageSize.width < 80 {
                    
                    let currenWidth: CGFloat = 80
                    
                    var cureenHeight = currenWidth / imageSize.width * imageSize.height
                    
                    if cureenHeight > 150 {
                        
                        cureenHeight = 150
                    }
                
                    imageSize = CGSize(width:currenWidth , height: cureenHeight)
                }
                
                self.snp.updateConstraints({ (make) in
                    
                    make.size.equalTo(imageSize).priority(.high)
                })
                
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                
                flowLayout.itemSize = imageSize
                
                return
            }
            
        }
        
        // 列数计算
        let cols = count > 3 ? 3 : count
        // 行数的计算
        let rowS = (count - 1) / 3 + 1
        // 配图的宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMarin
        // 配图的高度
        let pictureViewHeight = CGFloat(rowS) * ItemWidth + CGFloat(rowS - 1) * ItemMarin
        // 当前配图的大小
        let pictureViewSize = CGSize(width: pictureViewWidth, height: pictureViewHeight)
        
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(pictureViewSize).priority(.high)
        }
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)

    }
    
}

extension WBHomePictureView :UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewCell_id, for: indexPath) as! WBHomePictureViewCell
        
        cell.pictInfo = picUrls![indexPath.item]
        
        return cell
        
    }
    
}


class WBHomePictureViewCell: UICollectionViewCell {
    
    fileprivate lazy var imageView: UIImageView = {
       
        let  imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        
        imageView.contentMode = .scaleAspectFill
        
        imageView.clipsToBounds = true

        return imageView
    }()
    
    var pictInfo: WBHomePicInfo? {
        
        didSet {
            
            if let imageUrl = pictInfo?.thumbnail_pic {
                
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage:UIImage(named: "timeline_image_placeholder"))
            
            }
        }
      
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in

            make.edges.equalTo(contentView)
        }
        
    }
    // 读取Plist文件数据
    private func readComposeData() {
        
        
    }
    
    
    
}
